<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更新基本资料</span>
    </div>

    <el-form ref="form" label-width="100px" :model="userInfo" :rules="abc">
      <el-form-item label="登录账号">
        <el-input v-model="userInfo.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userInfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userInfo.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUser">确认修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updateUserAPI } from '@/api/user'
export default {
  data() {
    return {
      // userInfo: {
      //   username: '',
      //   nickname: '',
      //   email: ''
      // },
      userInfo: { ...this.$store.state.user.user },
      abc: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 1, max: 10, message: '昵称长度为1-10位', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确格式的邮箱', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    updateUser() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // console.log('验证成功')
        const { data: res } = await updateUserAPI(this.userInfo)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.$store.dispatch('user/getUser')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.userInfo = { ...this.$store.state.user.user }
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 400px;
}
</style>
